package com.wangxue.stock.service.impl;

import com.google.common.base.Strings;
import com.wangxue.stock.common.enums.ResponseCode;
import com.wangxue.stock.mapper.SysUserMapper;
import com.wangxue.stock.pojo.SysUser;
import com.wangxue.stock.service.UserService;
import com.wangxue.stock.utils.IdWorker;
import com.wangxue.stock.vo.req.LoginReqVo;
import com.wangxue.stock.vo.resp.LoginRespVo;
import com.wangxue.stock.vo.resp.R;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wangxue
 * @Date 2022/05/18
 * user业务实现类，用户服务，服务接口实现
 *
 */

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 分布式生成唯一id
     */
    @Autowired
    private IdWorker idWorker;

    /**
     * 登录功能实现，转换前后端数据
     *
     * @param vo
     * @return * @return R<LoginRespVo>
     * @author wangxue
     * @date 2022/5/18 17:38
     */
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {

        //判断输入的vo数据或者账号或者密码是否为空
        if(vo == null || Strings.isNullOrEmpty(vo.getUsername()) || Strings.isNullOrEmpty(vo.getPassword())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }

        //验证码校验
        //获取redis中的rkey对应的code验证码
        String rCode = (String) redisTemplate.opsForValue().get(vo.getRkey());
        //校验
        if(Strings.isNullOrEmpty(rCode) || !rCode.equals(vo.getCode())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //redis清除key
        redisTemplate.delete(vo.getRkey());
        //根据用户名查询用户信息
        SysUser user  = this.sysUserMapper.findByUsername(vo.getUsername());

        //判断用户是否存在，存在密码校验对比
        if(user == null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //组装登录成功数据
        LoginRespVo respVo = new LoginRespVo();
        System.out.println("查询user结果"+user);
        //属性名称和类型必须相同，否则copy不到
        BeanUtils.copyProperties(user,respVo);
        return R.ok(respVo);
    }
    /**
     * 生成验证码
     *   map结构：
     *        code: xxx,
     *        rkey: xxx
     *
     * @return R<Map>
     * @author wangxue
     * @Date 2022/5/19
     */
    @Override
    public R<Map> generateCaptcha() {
        //1.生成4位数字验证码
        String checkCode = RandomStringUtils.randomNumeric(4);
        // 2.获取全局唯一id
        String rkey = String.valueOf(idWorker.nextId());
        //验证码存入redis中设置有效时间为60s
        redisTemplate.opsForValue().set(rkey,checkCode,60, TimeUnit.SECONDS);
        //3.组装数据
        HashMap<String,String > map = new HashMap<>();
        map.put("code",checkCode);
        map.put("rkey",rkey);

        return R.ok(map);
    }
}
